package com.lanxi.nbpaytest.Controller;

import com.alibaba.fastjson.JSON;
import com.lanxi.nbpaytest.RandomUtils;
import com.lanxi.nbpaytest.Service.PayService;
import com.lanxi.nbpaytest.requestparam.DrawBackRequest;
import com.lanxi.nbpaytest.requestparam.PayStatusRequest;
import com.lanxi.nbpaytest.requestparam.QueryBody;
import com.lanxi.nbpaytest.resultparam.BackParam;
import com.lanxi.nbpaytest.resultparam.ResultParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Map;


/**
 * @Author mintaoyu
 * Date on 2020-02-25  15:02
 */
@Slf4j
@Controller
public class PayController {

    private static BackParam backParam = null;
    private static BackParam backParamTest = null;

    @Autowired
    PayService payService;

    @Value("${lanxi.appid}")
    private String appId;

    @Value("${pay.url}")
    private String reqUrl;

    @Value("${notifyUrl}")
    private String notifyUrl;

    @Value("${payFrontUrl}")
    private String payFrontUrl;


    @RequestMapping("/index")
    public String index() {
        return "index";
    }


    /**
     * 查询支付结果
     *
     * @return
     */
    @PostMapping("/payStatus")
    @ResponseBody
    public ResultParam payStatus() {
        log.info("调用payStatus接口");
        log.info("backParam" + backParam);
        ResultParam resultParam = new ResultParam();
        if (backParam != null) {
            resultParam.setData(backParam);
            resultParam.setResultMsg("获取成功");
            resultParam.setResultCode("200");
        }
        return resultParam;
    }

    /**
     * 一期支付模拟
     *
     * @param response
     * @param request
     */
    @ResponseBody
    @RequestMapping("/pay")
    public void pay(HttpServletResponse response, HttpServletRequest request, String transAmt, String integralNum) {

        log.info("开始进入pay接口");
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = df.format(System.currentTimeMillis());
        // 蓝喜生成订单 测试 merId：333021258121280  生产：313331090089000
        String body = "{\"channelType\":\"00\",\"merDateTime\":\"" + format + "\",\"merSeqNo\":\""
                + RandomUtils.randomFlowNo()
                + "\",\"merId\":\"333021258121280\",\"notifyUrl\":" + notifyUrl + ",\"orderDesc\":\"miaoshu\",\"payFrontUrl\":" + payFrontUrl + ",\"platformId\":\"NBCB999999999\",\"terminalType\":\"01\",\"transAmt\":\"" + transAmt + "\",\"currency\":\"156\",\"rechargeType\":\"15\",\"integralNum\":\"" + integralNum + "\"}";


        log.info("订单body" + body);
        payService.init();
        String signMsg = payService.sign(body);
        String html = payService.createAutoFormSubmitHtml(appId, reqUrl, body, signMsg);
        log.info("html:" + html);
        java.io.PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (out != null) {
            out.write(html);
            out.flush();
            out.close();
        }
    }

    @ResponseBody
    @RequestMapping("/testEn")
    public void testEn(){
        String body = "{\"channelType\":\"00\",\"merDateTime\":\"" + "111" + "\",\"merSeqNo\":\""
                + RandomUtils.randomFlowNo()
                + "\",\"merId\":\"333021258121280\",\"notifyUrl\":" + "111" + ",\"orderDesc\":\"描述\",\"payFrontUrl\":" + "111" + ",\"platformId\":\"NBCB999999999\",\"terminalType\":\"01\",\"transAmt\":\"" + "111" + "\",\"currency\":\"156\",\"rechargeType\":\"15\",\"integralNum\":\"" + "111" + "\"}";
        log.info("订单body" + body);
        payService.init();
        String sign = payService.sign(body);
        boolean validate = payService.validate(body, sign);
        if (validate){
            log.info("验证成功");
        }else {
            log.info("验证失败");
        }

    }



    /**
     * 交易状态查询
     *
     * @param merDate  被查询交易的商户端交易日期
     * @param merSeqNo 被查询交易的商户端交易流水号
     * @return
     */
    @ResponseBody
    @GetMapping("/queryPayStatus")
    public String queryPayStatus(@RequestParam("merDate") String merDate, @RequestParam("merSeqNo") String merSeqNo) throws ParseException {
        log.info("开始进入queryPayStatus接口");
        QueryBody queryBody = new QueryBody();
        PayStatusRequest request = new PayStatusRequest();
        request.setChannelType("00");
        request.setMerDate(merDate);
        request.setMerId("333021258121280");
//        request.setMerId("313331090089000");
        request.setMerSeqNo(merSeqNo);
        request.setPlatformId("NBCB999999999");
        String body = JSON.toJSONString(request);
        payService.init();
        String signMsg = payService.sign(body);
        queryBody.setBody(body);
        queryBody.setSignMsg(signMsg);
        String querybodyJSON = JSON.toJSONString(queryBody);
        log.info("交易body" + querybodyJSON);
        String post = payService.post(appId, "http://aap-test.nbcb.com.cn:20380/pay/api/v1/tradeQuery", querybodyJSON);
//        log.info("交易返回报文：" + post);
//        JSONObject object = JSONObject.parseObject(post);
//        String bodyString = (String) object.get("body");
//        PayStatusResult result = JSON.parseObject(bodyString, PayStatusResult.class);
        log.info("查询结果" + post);
//        ResultParam resultParam = new ResultParam();
//        if (result != null) {
//            resultParam.setResultCode("200");
//            resultParam.setResultMsg("获取成功");
//            resultParam.setData(result);
//        } else {
//            resultParam.setResultCode("400");
//            resultParam.setResultMsg("获取失败");
//            resultParam.setData(null);
//        }
        return post;

    }

    /**
     * 退款
     *
     * @param orgMerDate  原支付交易日期 yyyy-MM-dd
     * @param orgMerSeqNo 原支付交易流水号
     * @param transAmt    现金金额
     * @return
     */
    @ResponseBody
    @GetMapping(value = "/drawback")
    public String drawback(String orgMerSeqNo, String orgMerDate, BigDecimal transAmt) {
        log.info("进入退款接口");
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = df.format(System.currentTimeMillis());
        DrawBackRequest request = new DrawBackRequest();
        QueryBody queryBody = new QueryBody();
        request.setChannelType("00");
        request.setMerDateTime(format);
//        request.setMerId("333021258121280");
        request.setMerId("333021258121280");
        request.setMerSeqNo(RandomUtils.randomFlowNo());
        request.setOrgMerDate(orgMerDate);
        request.setOrgMerSeqNo(orgMerSeqNo);
        request.setPlatformId("NBCB999999999");
        request.setTransAmt(transAmt);
        String body = JSON.toJSONString(request);
        payService.init();
        String signMsg = payService.sign(body);
        queryBody.setBody(body);
        queryBody.setSignMsg(signMsg);
        String querybodyJSON = JSON.toJSONString(queryBody);
        log.info("退款body" + querybodyJSON);
//        String post = payService.post(appId, "http://aap-test.nbcb.com.cn:22780/pay/api/v1/tradeRefund", querybodyJSON);
        String post = payService.post(appId, "http://10.23.90.13:9445/NBNH/pay/api/v1/tradeRefund", querybodyJSON);
        log.info("退款返回报文：" + post);
//        JSONObject object = JSONObject.parseObject(post);
//        String bodyString = (String) object.get("body");
//        DrawBackResult result = JSON.parseObject(bodyString, DrawBackResult.class);
//        log.info("退款查询结果" + post);
//        ResultParam resultParam = new ResultParam();
//        if (result != null) {
//            resultParam.setResultCode("200");
//            resultParam.setResultMsg("获取成功");
//            resultParam.setData(result);
//        } else {
//            resultParam.setResultCode("400");
//            resultParam.setResultMsg("获取失败");
//            resultParam.setData(null);
//        }
        return post;
    }

    /**
     * 后端回调
     *
     * @param objectMap
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/fallBack")
    public ResultParam fallBack(@RequestBody Map<Object, Object> objectMap) {
        String body = objectMap.get("body") + "";
        log.info("body:" + body);
        String signMsg = objectMap.get("signMsg") + "";
        log.info("signMsg:" + signMsg);
        log.info("开始进入fallBack接口");
        ResultParam resultParam = new ResultParam();
        boolean validate = payService.validate(body, signMsg);
        log.info("验证是否通过" + validate);
        if (validate) {
            resultParam.setResultCode("200");
            resultParam.setResultMsg("支付成功");
            BackParam params = JSON.parseObject(body, BackParam.class);
            log.info("params:" + params);
            backParam = params;
            resultParam.setData(params);
        } else {
            resultParam.setResultCode("500");
            resultParam.setResultMsg("验签失败");
            resultParam.setData(null);
        }
        return resultParam;
    }

    /**
     * 前端回调
     *
     * @return
     */
    @RequestMapping("/payFrontUrl")
    public String payFrontUrl() {
        return "show";
    }


    public static void main(String[] args) throws UnsupportedEncodingException {
        String name = "12";
        byte[] bytes = name.getBytes();
        System.out.println(bytes);


//        byte[] byteArray = {"-26","B",'@','6','e','0','e','0','4','8','a'};

        byte[] byteArray = {-26, -104, -97, -26, -100, -97, -28, -70, -108};

        String str = new String(byteArray);
        System.out.println(str);

        byte[] bytes1 = {-26, -104, -97, -26, -100, -97, -28, -70, -108};
        String abc = new String(bytes1, "UTF-8");
        System.out.println(abc);
    }
}
